/*
 * @Description: 
 * @Author: cw
 * @LastEditors: cw
 * @Date: 2019-04-08 16:30:36
 * @LastEditTime: 2019-04-25 18:22:00
 */
let moment = require('moment');
let DataHelper=require("./DataHelper");
let DataFetcher=require("./DataFetcher");
const STR_FORMAT = require('string-format');
let tNetworks = ["Admob","Facebook"];

if(!global.FILE){
    global.FILE={};
}

let fs = {
    existsSync:function(sFileName){
        return DataHelper.Instance.FileExists(sFileName);
    },
    mkdirSync:function(){

    },
    readFile:function(sFileName,pCallback){
        DataHelper.Instance.GetData([sFileName],(err,tResp)=>{
            if(err){
                pCallback(err);
            }else{
                if( tResp.Data ){
                    pCallback(null,tResp.Data)
                }else{
                    pCallback(err);
                }
            }
        });
    },
    writeFile:function(sFileName,sFileData,pCallback){
        DataHelper.Instance.Begin("SET");
        DataHelper.Instance.SetData(sFileName,sFileData);
        DataHelper.Instance.Flush(pCallback);
    }
};

function DataMgr() {
    this._tFileData={};
    this._T_CONF={};
    this._tGPToken=null;
    this._oTimer=null;
}

DataMgr.prototype.Init=function(tConfig){
    this._T_CONF=tConfig;
    this._tFileData={};
    this._tGPToken=null;
    DataHelper.Instance.Init((tDirs)=>{
        this.SyncAllFileDatas(tDirs);
    });
    this.DoKeepHeart();
};

DataMgr.prototype.GetFileData=function(sFileName){
    return this._tFileData[sFileName];
}

DataMgr.prototype.SyncAllFileDatas=function(tDirs){
    for(let sFileName in tDirs){
        fs.readFile(sFileName,(sErr,tData)=>{
            if(!sErr&&tData){
                console.log("Sync file data OK:"+sFileName);
                this._tFileData[sFileName]=tData[sFileName];
            }
        });
    }
}

DataMgr.prototype.Clear=function(){
    this._T_CONF={};
    this._tGPToken=null;
    DataHelper.Instance.Clear();
    if(this._oTimer1){
        clearInterval(this._oTimer1);
        this._oTimer1=null;
    }
    if(this._oTimer2){
        clearInterval(this._oTimer2);
        this._oTimer2=null;
    }
    this.DoKeepHeart();
};

DataMgr.prototype.Start=function(){
    let self = this;
    setTimeout(() => {
        self.DoCheckAndFetech();
    }, 4000);
    if(this._oTimer1){
        clearInterval(this._oTimer1);
        this._oTimer1=null;
    }
    if(this._oTimer2){
        clearInterval(this._oTimer2);
        this._oTimer2=null;
    }
    this._oTimer1=setInterval(()=>{
        self.DoKeepHeart();
    },30000);
    this._oTimer2=setInterval(()=>{
        self.DoCheckAndFetech();
    },60000*30);
};

DataMgr.prototype.Print=function(){
    console.log("PRINT");
};

DataMgr.prototype.SetGooglePlayAuthToken=function(sToken){
    this._sGoogleAuthToken = sToken;
}

DataMgr.prototype.GetDateAllNetworkData=function(sDate,pCallback){
    let tData = {}
    for(let sNetwork of tNetworks){
        tData[sNetwork]=this.GetNetworkDateData(sDate,sNetwork);
    }
    pCallback(tData);
}

DataMgr.prototype.GetNetworkDateData=function(sDate,sNetwork){
    let sFileName = STR_FORMAT("./saved_data/{}/{}.json",sDate,sNetwork);
    return this._tFileData[sFileName];
}

DataMgr.prototype.GetDateHalfNetworkData=function(sDate,pCallback){
    let tData = {}
    for(let sNetwork of tNetworks){
        if(sNetwork!="AdMob"){
            tData[sNetwork]=this.GetNetworkDateData(sDate,sNetwork);
        }
    }
    pCallback(tData);
}

DataMgr.prototype.GetDateSavedAllData = function(sDate,pCallback){
    let sDateDataFileName = "./saved_data/"+ sDate + "/All_Data.json";
    fs.readFile(sDateDataFileName,(err,data)=>{
        if(!err){
            pCallback(data[sDateDataFileName]);
        }else{
            let sDateHalfDataFileName = "./saved_data/"+ sDate + "/Half_Data.json";
            fs.readFile(sDateHalfDataFileName,(err2,data2)=>{
                if(!err2){
                    pCallback(data2[sDateHalfDataFileName]);
                }else{
                    pCallback();
                }
            });
        }
    })
}

DataMgr.prototype.GetDateAllData = function(sDate){
    let sDateDataFileName = "./saved_data/"+ sDate + "/All_Data.json";
    if(this._tFileData[sDateDataFileName]){
        return this._tFileData[sDateDataFileName];
    }else{
        let sDateHalfDataFileName = "./saved_data/"+ sDate + "/Half_Data.json";
        if(this._tFileData[sDateHalfDataFileName]){
            return this._tFileData[sDateHalfDataFileName];
        }
    }
}


DataMgr.prototype.DoKeepHeart=function(){
    console.log("DoKeepHeart")
    DataHelper.Instance.GetData(["GP_Token"],(err,tResp)=>{
        if(!tResp){
            return;
        }
        console.log("--GP Token")
        console.log(tResp)
        this._tGPToken=tResp.GP_Token;
    })
}

DataMgr.prototype.DoCheckAndFetech=function(){
    let oBeginTime = moment();
    let self = this;
    let nQueryAdmob=0;
    let nQueryFB=0;
    for(let i=0;i<15;++i){
        let sDate = oBeginTime.subtract(1,"day").format("YYYY-MM-DD");
        let sAdmobFileName = "./saved_data/"+ sDate + "/Admob.json";
        if(!fs.existsSync(sAdmobFileName)){
            setTimeout(() => {
                self.DoCheckAndFetchAdmob(sDate);
            },10000*nQueryAdmob);
            nQueryAdmob++;
        }else{
            fs.readFile(sAdmobFileName,(sErr,tData)=>{
                if(!sErr&&tData){
                    console.log('read file data:'+sAdmobFileName)
                    this.SaveDataToLocal(sAdmobFileName,tData[sAdmobFileName],sDate);
                }
            });
        }

        let sFBFileName = "./saved_data/"+ sDate + "/Facebook.json";
        if(!fs.existsSync(sFBFileName)){
            setTimeout(() => {
                self.DoCheckAndFetchFacebook(sDate);
            },10000*nQueryFB);
            nQueryFB++;
        }else{
            fs.readFile(sFBFileName,(sErr,tData)=>{
                if(!sErr&&tData){
                    console.log('read file data:'+sFBFileName)
                    this.SaveDataToLocal(sFBFileName,tData[sFBFileName],sDate);
                }
            });
        }
    }   
};

DataMgr.prototype.DoCheckAndFetchAdmob=function(sDate){
    console.log("DoCheckAndFetchAdmob--1--"+sDate);
    if(this._tGPToken==null){
        return;
    }
    console.log("DoCheckAndFetchAdmob--2--"+sDate);
    let sFileName = "./saved_data/"+ sDate + "/Admob.json";
    if(!fs.existsSync(sFileName)){
        console.log("DoCheckAndFetchAdmob--3--"+sDate);
        DataFetcher.RequestAdmobData(sDate,this._tGPToken,(err,tData)=>{
            console.log("DoCheckAndFetchAdmob--4--"+sDate);
            if(!err){
                console.log("Admob Data OK: "+sDate);
                this.SaveDataToFile(sFileName,tData,sDate);
            }else{
                console.log(err)
            }
        });   
    }
} 

DataMgr.prototype.DoCheckAndFetchFacebook=function(sDate){
    console.log("DoCheckAndFetchFacebook: "+sDate);
    let sFileName = "./saved_data/"+ sDate + "/Facebook.json";
    let tFacebookDateData = {}
    let tDataQueryFinished={};
    if(!fs.existsSync(sFileName)){
        let nCount = 0;
        for(let sAppName in this._T_CONF.Keys.Facebook){
            setTimeout(()=>{ 
                let tConf = this._T_CONF.Keys.Facebook[sAppName];
                if(tConf){
                    nCount++;
                    DataFetcher.RequestFacebookData(sDate,tConf.Token,tConf.ID, (err,tData)=>{
                        tDataQueryFinished[sAppName]=true
                        console.log("FB Data OK: "+sDate+" "+sAppName);
                        if(tData){
                            tFacebookDateData["Android_"+tConf.ID] = tData.android;
                            tFacebookDateData["IOS_"+tConf.ID] = tData.ios;  
                        }
                        for(let sName in this._T_CONF.Keys.Facebook){
                            if(!tDataQueryFinished[sName]){
                                return;
                            }
                        }
                        this.SaveDataToFile(sFileName,tFacebookDateData,sDate);
                    });    
                }   
            },nCount*2000);
        }
    }
}

DataMgr.prototype.DoCheckAndSaveDateData=function(sDate){
    console.log("DoCheckAndSaveDateData:"+sDate);
    for(let sNetworkName of tNetworks){
        let sFileName = "./saved_data/"+ sDate + "/" +sNetworkName+ ".json";
        if(!this.GetFileData(sFileName)){
            return;
        }
    }
    this.GetDateAllNetworkData(sDate,(tData)=>{
        if(tData&&Object.keys(tData).length>0){
            let sDateDataFileName = "./saved_data/"+ sDate + "/All_Data.json";
            this._tFileData[sDateDataFileName]=tData;
            if(!fs.existsSync(sDateDataFileName)){
                fs.writeFile(sDateDataFileName,tData,(err)=>{
                    if(!err){
                        console.log("save:"+sDateDataFileName);
                    }
                });
            }
        }
    });
}

DataMgr.prototype.DoCheckAndSaveHalfDateData=function(sDate){
    for(let sNetworkName of tNetworks){
        if(sNetworkName != "Admob"){
            let sFileName = "./saved_data/"+ sDate + "/" +sNetworkName+ ".json";
            if(!this.GetFileData(sFileName)){
                return;
            }
        }
    }
    this.GetDateHalfNetworkData(sDate,(tData)=>{
        let sDateDataFileName = "./saved_data/"+ sDate + "/Half_Data.json";
        if(tData&&Object.keys(tData).length>0){
            this._tFileData[sDateDataFileName]=tData;
            if(!fs.existsSync(sDateDataFileName)){
                fs.writeFile(sDateDataFileName,tData,(err)=>{
                    if(!err){
                        console.log("save:"+sDateDataFileName);
                    }
                });
            }
        }
    });
}

DataMgr.prototype.SaveDataToFile = function(sFileName,tData,sDate){
    if(!tData){
        return
    }
    this._tFileData[sFileName]=tData;
    if(!fs.existsSync(sFileName) ){
        fs.writeFile(sFileName,tData,(err)=>{
            if(!err){
                console.log("----save file ok---"+sFileName)
            }else{
                console.log("save data err: "+err);
            }
        });
    }
    this.DoCheckAndSaveHalfDateData(sDate);
    this.DoCheckAndSaveDateData(sDate);
}

DataMgr.prototype.SaveDataToLocal = function(sFileName,tData,sDate){
    if(!tData){
        return
    }
    this._tFileData[sFileName]=tData;
    this.DoCheckAndSaveHalfDateData(sDate);
    this.DoCheckAndSaveDateData(sDate);
}

DataMgr.prototype.refetchSevenDay = function(){
    // let oBeginTime = moment();
    // for(let i=0;i<7;++i){
    //     let sDate = oBeginTime.subtract(1,"day").format("YYYY-MM-DD");
    //     let sDirName = "./saved_data/"+sDate
    //     if(fs.existsSync(sDirName)){
    //         for(let sNetworkName of tNetworks){
    //             let sFileName = "./saved_data/"+sDate+"/"+sNetworkName+".json";
    //             if(fs.existsSync(sFileName)){
    //                 fs.unlinkSync(sFileName);
    //             }
    //         }
    //         let sHalfData =  "./saved_data/"+sDate+"/Half_Data.json";
    //         if(fs.existsSync(sHalfData)){
    //             fs.unlinkSync(sHalfData);
    //         }
    //         let sAllData =  "./saved_data/"+sDate+"/All_Data.json";
    //         if(fs.existsSync(sAllData)){
    //             fs.unlinkSync(sAllData);
    //         }
    //         fs.rmdirSync(sDirName);
    //     }
    // }
    // let self = this;
    // let oFetchBeginTime = moment();
    // for(let i=0;i<7;++i){
    //     let sDate = oFetchBeginTime.subtract(1,"day").format("YYYY-MM-DD");
    //     if(!fs.existsSync("./saved_data/"+sDate)){
    //         fs.mkdirSync("./saved_data/"+sDate);
    //     }
    //     setTimeout(() => {
    //         self.DoCheckAndFetchAdmob(sDate);
    //         self.DoCheckAndFetchFacebook(sDate);
    //     },3500*i);
    // }
}

if(!global.__oDataMgr){
    global.__oDataMgr= new DataMgr();
}

module.exports = {
    Instance: global.__oDataMgr
}